const distanceX = 904; //1383
const distanceY = 468; //1257
const firstCarX = 480; //生涯列表771,赛事列表880
const firstCarY = 790;

const raceFirstX = 247;  
const raceFirstY = 802;  
const raceDistanceX = 933; 
const raceDistanceY = 478; 
const middleX = 1047;
//车辆列表根据中心车辆偏移，负数向左，0位于中间，正数向右
const carListLocate = 0;   

//多车可用时会自动将最近使用的车辆滚动到中央，根据中央车辆排布序号如下
//    -2     0     2
//    -1     1     3
const raceCarNum = [1,3]

var bronze = {
    point: {
        x: 1980,
        y: 300
    },
    cars: {
        nums: [12, 10, 9, 8, 7]
    }
};

var silver = {
    point: {
        x: 2160,
        y: 300
    },
    cars: {
        nums: [14, 13, 12, 11, 9, 8, 7]
    }
};

var gold = {
    point: {
        x: 2340,
        y: 300
    },
    cars: {
        nums: [16, 15, 14, 13, 12, 11]
    }
};

var platinum = {
    point: {
        x: 2520,
        y: 300
    },
    cars: {
        nums: [13, 12, 11, 10, 9, 7]
    }
};

var legend = {
    point: {
        x: 2700,
        y: 300
    },
    cars: {
        nums: [13, 12, 11, 9, 8, 7, 5, 4, 3]
    }
};

var rank = platinum;
var scoreRank = null;
var mpMode = false;    //是否进行多人模式中
var mpNum = 0;
const maxMpNums = 12;   //多人场数，达到后切换模式
var orientation = [0,1];

mainEntrence();

// 程序主入口
function mainEntrence() {
    deviceInfo();
    eventListener();
    sleep(2000);

    // 运行主函数
    main();
    // isRunStart();

}


function eventListener() {
    threads.start(function () {
        // 启用按键监听
        events.observeKey();
        // 监听音量上键按下
        events.onKeyDown("volume_down", function (event) {
            toastLog("程序手动退出");
            threads.shutDownAll();
            exit();
        });
    });
}


function deviceInfo() {
    auto();
    if (!requestScreenCapture()) {
       toast('请求截图失败，程序结束');
       exit();
    }
  // 调整屏幕亮度
    device.setBrightness(0);
}

function main() {
    toast("开始运行");
    reachRacePage();
}

//进入每日赛事
function reachRacePage(){
    mpMode = false;
    mpNum = 0;
    dailyRacePage();
    click(1500,600);
    sleep(2000);
    //swipe(2500,1300,500,1300,800);
    sleep(1000);
    click(1500,1300);
    sleep(800);
    click(1500,1300);
    sleep(2500);
    startFindCar();
}

function dailyRacePage(){
    var mpBtn = getPointColor(captureScreen(), 1100, 1300);
    if (!colors.isSimilar(mpBtn, "#ffffffff", 5)) {
        click(1100, 1300);
        sleep(1000);
    }
    click(1100, 1300);
    sleep(3500);
}

function startFindCar() {
    clickContinue();
    sleep(2500);

    var choosed = findRaceCar();
    if(choosed){
        sleep(3000);
    }else{
        //车辆都没油，回到主页
        clickHome();
        return;
    }
    checkTouchDrive();
    // 开始
    click(2400, 1280);
    sleep(5000);

    var leftBtn = getPointColor(captureScreen(), 650, 1100);
    if (colors.isSimilar(leftBtn, "#ffc3fb12")) {
        //出现补票弹窗，回到主页
        back();
        sleep(1500);
        clickHome();
    } else {
        // 开跑
        runUtilEnd();
    }

}

//寻找赛事用车
function findRaceCar(){
    for(i=0;i<raceCarNum.length;i++){
       var pos = raceCarNum[i];
       var x = middleX + ((pos >= 0 ? pos : -2) / 2) * raceDistanceX + carListLocate * raceDistanceX;
       var y = raceFirstY + abs((num - 1) % 2) * raceDistanceY;
       toast(x);
       var raceCarSelected = selectCar(x, y);
       if (raceCarSelected) {
           toast("选车完成");
           carListLocate = pos < 0 ? 1 : (pos > 1) ? -1 : 0
           return true;
       }
    }
    return false;
}

function reachMpRace(){
    mpMode = true;
    switchMpPage();
}

function switchMpPage() {
    var mpBtn = getPointColor(captureScreen(), 1600, 1300);
    if (!colors.isSimilar(mpBtn, "#ffffffff", 5)) {
        click(1600, 1300);
        sleep(1000);
    }
    click(1800, 500);
    sleep(2500);
    startMp();
}

function startMp() {
    click(1400, 1300);
    sleep(4000);
    if(scoreRank == null){
        checkScoreRank();
    }
    toast("开始选车");
    rank = scoreRank;
    selectInCarPage();
    runUtilEnd();
}

//检查当前最高段位
function checkScoreRank(){
    var finish = false
    scoreRank = legend;
    do{
        click(scoreRank.point.x, scoreRank.point.y);
        sleep(2000);
        click(firstCarX, firstCarY);
        sleep(2500);
        var upgradeBtn = getPointColor(captureScreen(), 260, 1300);
        if(colors.isSimilar(upgradeBtn,"#ffffffff")){
            finish = true;
        }else{
            if (scoreRank == legend) {
                scoreRank = platinum;
            } else if (scoreRank == platinum) {
                scoreRank = gold;
            } else if (scoreRank == gold) {
                scoreRank = silver;
            } else if (scoreRank == silver) {
                scoreRank = bronze;
                finish = true;
            }
        }
        back();
        sleep(3000);
    }while(!finish);
}

function selectInCarPage() {
    // 选车
    chooseModeAndCar();
    sleep(2500);
    checkTouchDrive();
    // 开始
    click(2400, 1280);
    checkConnect();
}

function checkTouchDrive() {
    sleep(1000);
    var tdPoint = findColor(captureScreen(), "#ffc0f814", {
        region: [2700, 1060, 120, 100],
        threshold: 10
    });
    toast(tdPoint);
    if (!tdPoint) {
        toast("打开自动驾驶");
        click(2700, 1100);
        sleep(2000);
    }
}

function checkConnect() {
    var connected = false;
    var times = 120;
    do {
        sleep(1000);
        var img = captureScreen();

         //出现赛道信息，视为开始
         var siteInfo = getPointColor(img, 300, 190);
         connected = colors.equals(topBg, "#ffffffff",10);
 

        var errorClose = getPointColor(img, 2500, 400);
        if (colors.isSimilar(errorClose, "#ffff0054", 6)) {
            click(2500, 400);
            sleep(3000);
            toast("重连选车");
            selectInCarPage();
            return;
        }
        
        //超时重新选车
        if(times == 0){
            back();
            sleep(3000);
            toast("重连选车");
            selectInCarPage();
            return;
        }else{
            times = times - 1;
        }
    } while (!connected);
}

function runUtilEnd() {
    toast("开始");
    var isEnd = false;
    do {
        sleep(1000);
        var continueBtn = getPointColor(captureScreen(), 2270, 1260);
        if (colors.isSimilar(continueBtn, "#ffc3fb12",10)) {
            isEnd = true;
        } else {
            if(mpMode){
                swipe(1960, 720, 1000, 720, 300);
                swipe(1960, 720, 1000, 720, 300);
            }else{
              swipe(1500,500,1960,500,300);  
            }
            click(2490, 1120);
        }
    } while (!isEnd);
    afterRun();
}

function chooseModeAndCar() {

    click(rank.point.x, rank.point.y);
    sleep(1500);

    var selected = false;
    var swiped = false;

    var numArray = rank.cars.nums;
    for (i = 0; i < numArray.length; i++) {
        var num = 0;
    
        if (numArray[i] > 6 && !swiped) {
            swipe(2959, 720, 200, 720, 4000);
            sleep(1500);
            swiped = true;
            if (numArray[i] > 12) {
                if(rank == legend){
                    swipe(2480, 720, 1500, 720, 4000);
                    sleep(1500);
                    selected = selectCar(2267, firstCarY + ((num - 1) % 2) * distanceY);
                    if (selected) {
                        toast("选车完成");
                        return;
                    }
                    click(rank.point.x, rank.point.y);
                    sleep(1500);
                    swiped = false;
                    continue;
                }
                swipe(2959, 720, 200, 720, 4000);
                sleep(1500);
            }
        } else {
            if (numArray[i] <= 6 && swiped) {
                click(rank.point.x, rank.point.y);
                sleep(1500);
                swiped = false;
            }
        }

        if (swiped) {
            do {
                num = numArray[i] - 6;
            } while (num > 6)
        } else {
            num = numArray[i];
        }
        var x = firstCarX + parseInt((num - 1) / 2) * distanceX;
        var y = firstCarY + ((num - 1) % 2) * distanceY;
        selected = selectCar(x, y);
        if (selected) {
            toast("选车完成");
            return
        }
    }

    changeRank();


}

function selectCar(x, y) {
    var img = captureScreen();
    var posData = checkForResolution(x + 10, y, img);
    var oil = images.pixel(img, posData.positionX, posData.positionY);
    toast(x + "," + y + "," + colors.toString(oil));
    if (colors.isSimilar(oil, "#ffc0f814", 40)) {
        click(x, y);
        return true;
    }
    return false;
}

function changeRank() {
    if (rank == legend) {
        rank = platinum;
    } else if (rank == platinum) {
        rank = gold;
    } else if (rank == gold) {
        rank = silver;
    } else if (rank == silver) {
        rank = bronze;
    }
    chooseModeAndCar();
}

function afterRun() {
    toast("跑完了");
    sleep(1000);
    clickContinue();
    sleep(4000);
    var continueBtn = getPointColor(captureScreen(), 2380, 1260);
    if (colors.isSimilar(continueBtn, "#ffc3fb12", 10)) {
        clickContinue();
        sleep(4000);
        clickContinue();
        sleep(2000);
        clickContinue();
    }

    if (mpMode) {
        //多人
        sleep(7500);
        mpNum = mpNum + 1;
        reward();
    } else {
        //寻车
        var home = false;
        do {
            clickContinue();
            sleep(5000);
            var leftTop = getPointColor(captureScreen(), 100, 100);
            home = colors.isSimilar(leftTop, "#ffffff", 8);
        } while (!home);
        startFindCar();
    }
    
    

}

function reward() {
    var startBtn = getPointColor(captureScreen(), 1300, 1300);
    if (colors.isSimilar(startBtn, "#ffc3fb12", 8)) {
        if(mpNum == maxMpNums){
            clickHome();
        }else{
            startMp();
        }
        return;
    }
    sleep(4000);
    var receive = getPointColor(captureScreen(), 1300, 1050);
    if (colors.isSimilar(receive, "#fffcd901", 10)) {
        toast("领取多人包");
        click(1400, 1050);
        sleep(4000);
        var home = false;
        do {
            clickContinue();
            sleep(5000);
            home = colors.isSimilar(getPointColor(captureScreen(), 100, 100),"#ffbd003f",8);
        } while (!home);
    }else{
        backToHome();
    }
    if(mpNum == maxMpNums){
        reachRacePage();
    }else{
        switchMpPage();
    }
}

function backToHome() {
    var home = false;
    do {
        back();
        sleep(3000);
        var leftTop = getPointColor(captureScreen(), 100, 100);
        home = colors.isSimilar(leftTop, "#ffbd003f",8);
    } while (!home);
}

function clickHome(){
    click(2830,70);
    sleep(2500);
    if(mpMode){
        reachRacePage();
    }else{
        reachMpRace();
    }
}

function clickContinue() {
    click(2500, 1260);
}
function checkForResolution(x, y, img) {
    var width = img.getWidth();
    var height = img.getHeight();
    if (width < height) {
        var e = x;
        x = y;
        y = e;
    }

    return {
        positionX: x,
        positionY: y
    };
}

function getPointColor(img, x, y) {
    var data = checkForResolution(x, y, img);
    return images.pixel(img, data.positionX, data.positionY);
}